package com.xtaller.easy.admin.controller.sys;

import com.alibaba.fastjson.JSONObject;
import com.xtaller.common.convert.J;
import com.xtaller.common.convert.L;
import com.xtaller.common.convert.V;
import com.xtaller.common.convert.W;
import com.xtaller.easy.admin.base.TApi;
import com.xtaller.easy.admin.config.R;
import com.xtaller.easy.admin.model.BaseUser;
import com.xtaller.easy.admin.model.BaseUserOrganizational;
import com.xtaller.easy.admin.model.SysOrganizational;
import com.xtaller.easy.admin.service.impl.BaseUserOrganizationalService;
import com.xtaller.easy.admin.service.impl.BaseUserService;
import com.xtaller.easy.admin.service.impl.SysOrganizationalService;
import com.xtaller.easy.admin.specification.Allot;
import com.xtaller.easy.admin.specification.OrganizationCreate;
import com.xtaller.easy.admin.specification.OrganizationUpdate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Taller on 2018/6/4
 */
@Api(tags = "部门/组织架构api")
@RestController
@RequestMapping("/v1/sys")
@CrossOrigin   //跨域服务注解
public class OrganizationalApi extends TApi {
    @Autowired private SysOrganizationalService organizationalService;
    @Autowired private BaseUserOrganizationalService userOrganizationalService;

    private Map<String,String> baseVerify(){
        Map<String,String> verify = new HashMap<>();
        verify.put("name","名称不能为空");
        verify.put("parentId","上级id不能为空");
        return verify;
    }

    @GetMapping("/organizational")
    @ApiOperation("读取部门/组织机构信息")
    public Object getOrganizational(){
        List<JSONObject> organizationals = J.o2l(organizationalService.getData());
        return R.ok("读取成功", L.list2Tree(organizationals, "0", 1));
    }

    @PostMapping("/organizational")
    @ApiOperation("创建部门/组织机构信息")
    public Object createOrganizational(@RequestBody OrganizationCreate object){
        JSONObject check = V.checkEmpty(baseVerify(), object);
        if(check.getBoolean("check"))
            return R.error(check.getString("message"));
        SysOrganizational model = J.o2m(object, SysOrganizational.class);
        model.setCreator(getUserIdByToken());
        // 唯一性判断
        if(organizationalService.exist(W.f(
                W.and("name", "eq", model.getName()),
                W.and("parentId", "eq", model.getParentId())
        )))
            return R.error("名称已经存在请更换");
        model = organizationalService.createModel(model);
        if(model == null)
            return R.error("创建失败,请稍后再试");
        return R.ok("创建成功", formatObject(model));
    }

    @PutMapping("/organizational")
    @ApiOperation("修改部门/组织机构信息")
    public Object updateOrganizational(@RequestBody OrganizationUpdate object){
        if(object.getId() == null)
            return R.error("数据Id不能为空");
        JSONObject check = V.checkEmpty(baseVerify(), object);
        if(check.getBoolean("check"))
            return R.error(check.getString("message"));
        SysOrganizational model = J.o2m(object, SysOrganizational.class);
        model.setCreator(getUserIdByToken());
        // 唯一性判断
        if(organizationalService.exist(W.f(
                W.and("name", "eq", model.getName()),
                W.and("id", "ne", model.getId()),
                W.and("parentId", "eq", model.getParentId())
        )))
            return R.error("名称已经存在请更换");
        model = organizationalService.updateModel(model);
        if(model == null)
            return R.error("修改失败,请稍后再试");
        return R.ok("修改成功", formatObject(model));
    }

    @DeleteMapping("/organizational/{id}")
    @ApiOperation("删除部门/组织机构信息")
    public Object deleteOrganizational(@ApiParam("需要删除的数据id") @PathVariable("id") String id){
        if(organizationalService.selectById(id) == null)
            return R.error("数据Id异常");
        if(organizationalService.checkParentId(id))
            return R.error("该数据下有子集数据，禁止删除！");
        if(organizationalService.deleteModel(id, getUserIdByToken()))
            return R.ok("删除成功");
        return R.error("删除失败请稍后再试");
    }

    @GetMapping("/organizational/auto/{organizationalId}-{key}")
    @ApiOperation("通过关键字")
    public Object autoKey(@ApiParam("部门组织架构id") @PathVariable("organizationalId") String organizationalId,
                          @ApiParam("自动完成的关键字长度必须大于3个字符") @PathVariable("key") String key){
        JSONObject object = new JSONObject();
        object.put("key", key);
        object.put("organizationalId", organizationalId);
        return R.ok(organizationalService.getByKey(object));
    }

    @PostMapping("/organizational/allot")
    @ApiOperation("给部门/组织分配员工")
    public Object allotOrganizational(@RequestBody Allot object){
        List<BaseUserOrganizational> check = userOrganizationalService.query(
                W.f(
                        W.field("id"),
                        W.and("organizationalId", "eq", object.getOrganizationalId()),
                        W.and("userId", "eq", object.getUserId())
                )
        );
        if(check.size() > 0)
            return R.error("该用户已在部门中");
        BaseUserOrganizational userOrganizational = J.o2m(object, BaseUserOrganizational.class);
        if(userOrganizationalService.createModel(userOrganizational) != null)
            return R.ok("分配成功");
        return R.error("分配失败");
    }
}
